package com.ruoyi.finance.protal.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.finance.livestreaming.entity.RewardWithVO;
import com.ruoyi.finance.livestreaming.vo.CounterChargeVO;
import com.ruoyi.finance.protal.service.ProtalUserService;
import com.ruoyi.finance.protal.utils.SzUserSession;
import com.ruoyi.finance.rules.entity.SzUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Slf4j
@Api(tags = "用户端操作")
@RestController
@RequestMapping("/protal")
public class ProtalUserController {

    @Autowired
    private ProtalUserService protalUserService;
    @Autowired
    private SzUserSession userSession;


    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public AjaxResult login(SzUser user, HttpServletRequest request){
        return protalUserService.login(user, request);
    }

    @ApiOperation(value = "用户注册-通过手机号")
    @PostMapping("/register")
    public AjaxResult register(SzUser user){
        return protalUserService.register(user);
    }

    @ApiOperation(value = "用户注册-通过手机号")
    @PostMapping("/inner/register")
    public AjaxResult innerRegister(SzUser user){
        return protalUserService.innerRegister(user);
    }

    @ApiOperation(value = "用户注册-发送验证码")
    @PostMapping("/sendRegisterCode")
    public AjaxResult SendRegisterCode(String phone){
        return protalUserService.SendRegisterCode(phone);
    }

    @ApiOperation(value = "个人中心-获取个人数据")
    @PostMapping("/getInfo")
    public AjaxResult getInfo(HttpServletRequest request){
        return protalUserService.getInfo(request);
    }

    @ApiOperation(value = "个人中心-上传用户头像")
    @PostMapping("/uploadPicture")
    public AjaxResult uploadPicture(MultipartFile file, HttpServletRequest request){
        return protalUserService.uploadPicture(file, request);
    }

    @ApiOperation(value = "个人中心-购买数字人直播-保存订单")
    @PostMapping("/saveSzOrder")
    public AjaxResult saveSzOrder(HttpServletRequest request){
        return protalUserService.saveSzOrder(request);
    }

    @ApiOperation(value = "个人中心-购买数字人直播-订单支付回调")
    @RequestMapping("/notify")
    public Map<String, String> receiveNotice(HttpServletRequest req, HttpServletResponse resp){
        Map<String, String[]> parameterMap = req.getParameterMap();

        if(parameterMap != null && !parameterMap.isEmpty()) {
            log.info("买家支付完毕");
            log.info("收到参数：{}", parameterMap);
            String data=req.getParameter("data");
            String sign=req.getParameter("sign");
            String signType =req.getParameter("signType");

            log.info("data的值为{}", data);
            log.info("sign的值为{}", sign);
            log.info("signType的值为{}", signType);

            JSONObject dataJson = JSONObject.parseObject(data);
            if (dataJson != null) {
                log.info("接收到的异步通知数据为：\n"+ JSONObject.toJSONString(dataJson, true));
                return protalUserService.receiveNotice(dataJson);
            } else {
                log.error("接收异步通知数据异常！！！dataJson:{}",dataJson);
            }

        }else{
            log.error("收到回调，参数为空");
        }
        return null;
    }

    @ApiOperation(value = "个人中心-购买数字人直播-订单轮询")
    @PostMapping("/orderPolling")
    public AjaxResult orderPolling(String orderId ,HttpServletRequest request){
        return protalUserService.orderPolling(orderId, request);
    }

    /**
     * H5支付 创建订单
     */
    @RequestMapping(value = "/createOrderH5")
    public AjaxResult createOrderH5(HttpServletRequest request, HttpServletResponse response){
        return protalUserService.createOrderH5(request, response);
    }


    /**
     * H5 余额变动详情
     * @param userId
     * @return
     */
    @GetMapping(value = "/finance/livestreaming/balanceDetailAdmin/{userId}")
    public AjaxResult balanceDetailAdmin(@PathVariable("userId") String userId){
        return protalUserService.balanceDetailAdmin(userId);
    }

    /**
     * H5 数字直播对冲
     * @param counterChargeVO
     * @return
     */
    @PostMapping(value = "/finance/livestreaming/mutualRecharge")
    public AjaxResult mutualRecharge(@RequestBody CounterChargeVO counterChargeVO){
        return protalUserService.mutualRechargeFree(counterChargeVO);
    }

    /**
     * 查询用户简单信息
     */
    @GetMapping("/rules/common/listSzUserSimple")
    public AjaxResult listSzUserSimple(@RequestParam(required = false) String nickname){
        List<Map<String, String>> data = protalUserService.listSzUserSimple(nickname);
        return AjaxResult.success(data);
    }

    /**
     * 数字直播对冲提现余额
     */
    @PostMapping("/finance/livestreaming/mutualRechargeBalance")
    public AjaxResult mutualRechargeBalance(@RequestBody CounterChargeVO vo){
        if (StringUtil.isNotEmpty(vo.getFromUser()) && StringUtil.isNotEmpty(vo.getToUser()) && StringUtil.isNotEmpty(vo.getPaymentPassword()) && vo.getPricing() != null){
            return protalUserService.mutualRechargeBalance(vo.getFromUser(), vo.getToUser(), vo.getPricing(),vo.getPaymentPassword());
        }else{
            return AjaxResult.error();
        }
    }

    @Log(title = "数字直播-礼物打赏", businessType = BusinessType.OTHER)
    @PostMapping("/finance/livestreamingUser/rewardWithGifts")
    public AjaxResult rewardWithGifts(@RequestBody RewardWithVO vo){
        if (vo.getUserId() == null || vo.getRewardedUser() == null || vo.getGiftId() == null || vo.getPrice() == null || vo.getCount() == null ||vo.getPrice().compareTo(BigDecimal.ZERO) == 0 || vo.getCount().compareTo(BigDecimal.ZERO) == 0) {
            return AjaxResult.error();
        }
        return protalUserService.rewardWithGifts(vo.getUserId(), vo.getRewardedUser(), vo.getGiftId(), vo.getPrice(), vo.getCount());
    }

    @Log(title = "新数字直播-礼物打赏", businessType = BusinessType.OTHER)
    @PostMapping("/inner/finance/livestreamingUser/rewardWithGifts")
    public AjaxResult innerRewardWithGifts(HttpServletRequest request,@RequestBody RewardWithVO vo){
        try {
            if (vo.getRewardedUser() == null || vo.getGiftId() == null
                    || vo.getPrice() == null || vo.getCount() == null ||vo.getPrice().compareTo(BigDecimal.ZERO) == 0
                    || vo.getCount().compareTo(BigDecimal.ZERO) == 0 || StringUtils.isBlank(vo.getToken())) {
                return AjaxResult.error();
            }
            SzUser userInfo = userSession.getCurrentUserInfo(request);
            vo.setUserId(userInfo.getId());
            return protalUserService.innerRewardWithGifts(vo);
        } catch (Exception e) {
            log.error("打赏失败：",e);
            return AjaxResult.error();
        }
    }


    @ApiOperation(value = "个人中心-查询下级用户")
    @GetMapping("/userInviteTree")
    public AjaxResult userInviteTree (HttpServletRequest request){
        return AjaxResult.success(protalUserService.userInviteTree(request));
    }

    /**
     * 用户购买记录 h5
     */
    @GetMapping(value = "/finance/livestreaming/purchaseRecordToAdmin/{userId}")
    public AjaxResult purchaseRecordToAdmin(@PathVariable Long userId) {
        Map<String, Object> stringObjectMap = protalUserService.purchaseRecord(userId);
        return AjaxResult.success(stringObjectMap);
    }

    /**
     * 购买数字直播
     */
    @GetMapping("/finance/livestreaming/buyLivestreaming")
    public AjaxResult buyLivestreaming(@RequestParam("userId") String userId, @RequestParam("parentId") String parentId) {
        return protalUserService.buyLivestreaming(userId,parentId);
    }

    /**
     * 派直播购买数字直播2
     */
    @GetMapping("/finance/livestreaming/buyLivestreaming2")
    public AjaxResult buyLivestreaming2(@RequestParam("userId") String userId) {
        return protalUserService.buyLivestreaming2(userId);
    }

    /**
     * 用户可提现余额细明
     * @param userId
     * @return
     */
    @GetMapping(value = "/finance/livestreaming/withdrawalBalance/{userId}")
    public AjaxResult withdrawalBalance(@PathVariable("userId") Long userId) {
        Map<String, Object> stringObjectMap =protalUserService.withdrawalBalance(userId);
        return AjaxResult.success(stringObjectMap);
    }


    /**
     * 用户绑定银行卡
     */
    @PostMapping(value = "/finance/livestreaming/saveBankCard")
    public AjaxResult saveBankCard(String realName, String cardId, String bankName, String bankAddress, HttpServletRequest request){
        if (StringUtil.isEmpty(realName) || StringUtil.isEmpty(cardId) || StringUtil.isEmpty(bankName) || StringUtil.isEmpty(bankAddress)){
            return AjaxResult.error("参数为空");
        }
        return protalUserService.saveBankCard(realName, cardId, bankName, bankAddress, request);
    }


    /**
     * 可提现余额提现
     * @return
     */
    @PostMapping(value = "/finance/livestreaming/withdraw")
    public AjaxResult withdraw(BigDecimal amount, String paymentPassword, HttpServletRequest request){
        if (StringUtil.isEmpty(paymentPassword)){
            return AjaxResult.error("支付密码不能为空");
        }

        if (amount == null){
            return AjaxResult.error("请输入提现金额");
        }

        return protalUserService.withdraw(amount, paymentPassword, request);
    }


    /**
     * 设置支付密码
     * @param paymentPassword
     * @param request
     * @return
     */
    @PostMapping(value = "/finance/livestreaming/setPaymentPassword")
    public AjaxResult setPaymentPassword(String paymentPassword, HttpServletRequest request){
        if (StringUtil.isEmpty(paymentPassword)){
            return AjaxResult.error("支付密码不能为空");
        }
        return protalUserService.setPaymentPassword(paymentPassword, request);
    }


    /**
     * 个人中心-提现记录查询
     * @param request
     * @return
     */
    @GetMapping("/finance/livestreaming/withdrawRecord")
    public AjaxResult withdrawRecord(HttpServletRequest request){
        return protalUserService.withdrawRecord(request);
    }

}
